package util;

public class SegmentManagerClass {
	private java.util.LinkedList<util.SegmentClass> storage = null;

	public SegmentManagerClass(){
		this.storage = new java.util.LinkedList<util.SegmentClass>();
	}

	public void clearSegments(){
		this.storage.clear();
	}
	public void addSegment(int a, int b){
		util.SegmentClass aux1, aux2;
		boolean found = false;
		int i = 0;
		if(a>b){
			return;
		}

		for(i=0; (i<storage.size() && !found); i++){
			aux1 = storage.get(i);
			if(aux1.a >= a){
				found = true;
				this.storage.add(i, new util.SegmentClass(a,b));
			}
		}
		if(!found){
			this.storage.add(i, new util.SegmentClass(a,b));
		}
		//solve solaps:
		int guarda = storage.size();
		aux1 = storage.get(0);
		for(i=1; i<guarda; i++){
			aux2 = storage.get(i);
			if((aux1.b <= aux2.b && aux1.b >= aux2.a-1) || (aux1.a <= aux2.b+1 && aux1.a >= aux2.a) || (aux1.a <= aux2.a && aux1.b >= aux2.b)){
				//Erase aux2 and update aux1
				aux1.a = min(aux1.a, aux2.a);
				aux1.b = max(aux1.b, aux2.b);
				storage.remove(i);
				i--;
				guarda--;
			}else{
				aux1 = aux2;
			}
		}

	}
	private int max(int a, int b){
		if(a>b){
			return(a);
		}else{
			return(b);
		}
	}
	private int min(int a, int b){
		if(a<b){
			return(a);
		}else{
			return(b);
		}
	}
	/**
	 * Returns -1 if not in any segment, otherwise returns the index of the segment
	 * @param d
	 * @return
	 */
	public int isInSegment(int d){
		util.SegmentClass aux;
		for(int i = 0; i<storage.size(); i++){
			aux = storage.get(i);
			if(aux.a<=d && aux.b>=d){
				return(i);
			}
		}
		return(-1);
	}
	public int isInSegment(short d){
		return(isInSegment(0x0000FFFF&d));
	}
	public util.SegmentClass[] getSegments(){
		return (this.storage.toArray(new util.SegmentClass[0]));
	}
	public void print(){
		System.out.printf("Segments: ");
		for(int i = 0; i<this.storage.size(); i++){
			System.out.printf("[0x%04X, 0x%04X]\t", this.storage.get(i).a, this.storage.get(i).b);
		}
		System.out.printf("\n");
	}
}
